<template>
  <div>
    <h2>被控端：共享你的屏幕</h2>
    <label>你的名称: <input v-model="myName" /></label>
    <button @click="init">开始共享</button>
    <video ref="localVideoRef" autoplay playsinline muted style="width: 500px;height: 300px;"></video>
    <video ref="remoteVideoRef" autoplay playsinline style="display: none;"></video>
  </div>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'

const myName = ref('')
const localVideoRef = ref(null)
const remoteVideoRef = ref(null)
let ws = null
let pc = null
let localStream = null

const init = async () => {
  if (!myName.value.trim()) return alert("请输入名称")

  try {
    localStream = await navigator.mediaDevices.getDisplayMedia({ video: true })
    localVideoRef.value.srcObject = localStream
  } catch (err) {
    console.error("屏幕共享失败", err)
    return
  }

  ws = new WebSocket("ws://10.10.0.80:10102/ws?name=" + myName.value.trim())

  ws.onmessage = async (msg) => {
    const data = JSON.parse(msg.data)
    if (data.type === 'offer') {
      await createPeerConnection(data.from)
      await pc.setRemoteDescription(new RTCSessionDescription(data.payload))
      const answer = await pc.createAnswer()
      await pc.setLocalDescription(answer)
      ws.send(JSON.stringify({
        type: 'answer',
        from: myName.value.trim(),
        to: data.from,
        payload: answer
      }))
    } else if (data.type === 'candidate') {
      if (pc && data.payload) {
        await pc.addIceCandidate(new RTCIceCandidate(data.payload))
      }
    }
  }
}

const createPeerConnection = async (remoteName) => {
  if (pc) return

  pc = new RTCPeerConnection()

  if (!localStream) {
    console.error("localStream 不存在，无法添加 track")
    return
  }

  localStream.getTracks().forEach(track => {
    pc.addTrack(track, localStream)
  })

  pc.onicecandidate = event => {
    if (event.candidate) {
      ws.send(JSON.stringify({
        type: 'candidate',
        from: myName.value.trim(),
        to: remoteName,
        payload: event.candidate
      }))
    }
  }
}

onUnmounted(() => {
  if (ws) {
    ws.close()
    ws = null
  }
  if (pc) {
    pc.close()
    pc = null
  }
  if (localStream) {
    localStream.getTracks().forEach(track => track.stop())
    localStream = null
  }
})
</script>
    